package com.example;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class ExampleMain {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
        persistEntity(emf);
        findAndRemoveEntity(emf);
        emf.close();
    }
    private static void findAndRemoveEntity(EntityManagerFactory emf){
        EntityManager em = emf.createEntityManager();
        /*Employee employee = em.find(Employee.class,1);*/
        Employee employee = em.getReference(Employee.class,1);
        em.remove(employee);
        System.err.println("after remove(): " + em.contains(employee));
        em.close();
    }
    private static void findDetachAndMergeEntity(EntityManagerFactory emf){
        EntityManager em = emf.createEntityManager();
        Employee employee = em.find(Employee.class,1);
        System.err.println("after find(): " + em.contains(employee));
        em.detach(employee);
        System.err.println("after detach(): " + em.contains(employee));
        employee = em.merge(employee);
        System.err.println("after merge(): " + em.contains(employee));
    }
    private static void findByReferenceAndDetachEntity(EntityManagerFactory emf){
        EntityManager em = emf.createEntityManager();
        Employee employee = em.getReference(Employee.class,1);
        System.err.println("after getReference(): " + em.contains(employee));
        em.detach(employee);
        System.err.println("after detach(): " + em.contains(employee));
        em.close();
    }
    private static void findAndDetachEntity(EntityManagerFactory emf){
        EntityManager em = emf.createEntityManager();
        Employee employee = em.find(Employee.class,1);
        System.err.println("after find(): " + em.contains(employee));
        em.detach(employee);
        System.err.println("after detach(): " + em.contains(employee));
        em.close();
    }
    private static void findByGetReference(EntityManagerFactory emf){
        EntityManager em = emf.createEntityManager();
        Employee employee = em.getReference(Employee.class,1);
        System.err.println("after find(): " + em.contains(employee));
        em.close();
    }
    private static void persistEntity(EntityManagerFactory emf){
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        Employee employee = new Employee("Sara","Admin");
        em.persist(employee);
        em.getTransaction().commit();
        em.close();
    }
}
